//
//  SEDatePicker.swift
//  EyeVisionForPatients
//
//  Created by qdsg on 2021/1/6.
//  Copyright © 2021 QDSG. All rights reserved.
//

import UIKit

protocol SEDatePickerDelegate: NSObjectProtocol {
    func datePickerConfirmBtnAction(dateStr: String)
}

class SEDatePicker: UIView {
    
    @IBOutlet weak var datePicker: UIDatePicker! {
        didSet {
            datePicker.backgroundColor = UIColor.white
            datePicker.minimumDate = Date()
            datePicker.addTarget(self, action: #selector(dateValueChanged(picker:)), for: .valueChanged)
        }
    }
    
    @IBOutlet weak var datePickerBgView: UIView! {
        didSet {
            datePickerBgView.origin.y = UIScreen.screenWidth
            show()
        }
    }
    
    @IBAction func cancelBtnAction(_ sender: UIButton) {
        dismiss()
    }
    
    @IBAction func confirmBtnAction(_ sender: Any) {
        delegate?.datePickerConfirmBtnAction(dateStr: dateStr)
        dismiss()
    }
    
    @IBAction func dismissBtnAction(_ sender: Any) {
        dismiss()
    }
    
    var dateStr: String = "" {
        didSet {
            if dateStr.isEmpty {
                datePicker.date = Date()
                dateStr = Date().toString(format: "yyyy-MM-dd HH:mm")
            } else {
                datePicker.date = Date.stringToDate(dateStr, dateFormat: "yyyy-MM-dd HH:mm")
            }
        }
    }
    
    weak var delegate: SEDatePickerDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setUI()
    }
    
    func setUI() {
        self.frame = UIScreen.main.bounds
        self.backgroundColor = UIColor.black.withAlphaComponent(0.2)
        self.alpha = 0
    }
    
    func show() {
        UIView.animate(withDuration: 0.2) {
            self.alpha = 1
            self.datePickerBgView.origin.y = 0
        }
    }
    
    func dismiss() {
        UIView.animate(withDuration: 0.2) {
            self.datePickerBgView.origin.y = UIScreen.screenHeight
        } completion: { (finish) in
            self.alpha = 0
            self.removeFromSuperview()
        }
    }
    
    @objc func dateValueChanged(picker: UIDatePicker) {
        dateStr = datePicker.date.toString(format: "yyyy-MM-dd HH:mm")
    }
}
